﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Ninject;
using Ninject.Activation.Caching;

namespace Reap.Common.Runtime.Dependency.Ninject.InRequestScope {
	/// <summary>
	/// 该类的作用就是 每次请求 在HTTP结束后 把实例给注销掉
	/// </summary>
	public sealed class OnePerRequestHttpModule : GlobalKernelRegistration, IHttpModule {

		public OnePerRequestHttpModule() {
			this.ReleaseScopeAtRequestEnd = true;
		}

		/// <summary>
		/// 把当前实例从HTTP上下文给清空 只保存HTTP请求作用域
		/// </summary>
		public void DeactivateInstancesForCurrentHttpRequest() {
			if (this.ReleaseScopeAtRequestEnd) {
				HttpContext context = HttpContext.Current;
				base.MapKernels((IKernel kernel)=>{
					kernel.Components.Get<ICache>().Clear(context);
				});
			}
		}

		public void Dispose() {
		}
		public void Init(HttpApplication application) {
			application.EndRequest += (object o, EventArgs e)=> {
				this.DeactivateInstancesForCurrentHttpRequest();
			};
		}

		public bool ReleaseScopeAtRequestEnd { get; set; }

	}
}
